/**
 * 寄送资料
 * @author zhangqiang
 * @date   2017/3/11
* karin 修改 2017/07/14
 */

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Toast, Button } from 'antd-mobile'
import style from './index.scss';
import 'style/mailingAddress.scss';
import AlipayJSOperation from '../../utils/alipayJSOperation';

import PageBar from '../../components/common/pageBar';
import { getCarInfo } from '../../actions/taxConfirmAction'
import getDataService from '../../services/getData'
import SendCxytjMessage from '../../utils/sendCxytjMessage';

class MailingAddress extends Component {
    constructor(props) {
        super(props);
        this.state = {
            payType: 'person', //默认寄送类型.person 个人；ems 邮政
            selectPayType:'person', // 兼容1.3
            ifYUE:true,
            latestData: {},// 用户地址
            latestAddrIndex: 0,// 用户地址条数
            hasList: 'no', //判断有没有用户地址，默认为no，有则是more
            mailAdd: { // 下游地址
                receiveAddress: '',
                receiveName: '',
                receivePhone: '',
                payType: '',
            }
        };

        this.orderId = this.props.params.orderId; // carId
    }

    /**
     * 生命周期
     */
    componentDidMount() {
        document.querySelector("title").innerHTML = "填写回寄地址";

        //隐藏标题栏右键
        AlipayJSOperation.setRightButtonStatus(false);
        //设置标题
        AlipayJSOperation.setTitle('填写回寄地址');
        //设置标题颜色
        AlipayJSOperation.setBarColor('#2FB3FE');

        this.getByOrderId(this.orderId); // 请求: 先请求下游地址，再拿用户地址列表

        SendCxytjMessage.sendMessage({ eventId: 'H5_P_Interspection_EnterSendbackaddresspage' });
    }

    /**
     *事件
     */
    /**
     * 请求用户地址
     */
    addressList() {
        let postData = {};
        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.addressList(postData).then(resultData => {
            if (resultData.code == 1000) {
                // validFlag =是否置灰的判断标记，0灰置,1有效（广东省内）,2未知
                Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
                let data = resultData.data.addressList
                let validFlagData = 'no'
                let index = localStorage.getItem('addressList_action') || 0
                if (data.length) {
                    validFlagData = this.state.payType != 'ems' || (this.state.payType == 'ems' && data[index].validFlag == 1) ? 'more' : 'no' // 自主：有地址就可以；邮政：地址第一个要有效
                }

                this.setState({
                    latestData: data[index],
                    hasList: validFlagData,
                    latestAddrIndex: data.length,
                })
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        });
    }

    /**
     * 请求下游地址
     */
    getByOrderId(orderId) {
        let postData = {
            orderId: orderId
        };
        Toast.hide(); //加载前 先关闭其他加载中的提示框 避免提示框一直存在的bug
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.getMailType(postData).then(resultData => {
            
            if (resultData.code == 1000) {
                let data = resultData.data
                if (data.mailType == "person") {
                    this.setState({
                        mailAdd: { // 下游地址
                            receiveAddress: data.receiveAddress,
                            receiveName: data.receiveName,
                            receivePhone: data.receivePhone,
                        }
                    });
                }
                this.setState({
                    ifYUE:data.carNumber.indexOf('粤') > -1 ? true : false,
                    payType: data.mailType // 年检类型这里如果为空，说明是1.3兼容的版本
                });
            }
            else {
                Toast.info(resultData.msg, 2);
            }
        }).then(() => this.addressList());
    }

    selectPayTypeFun (payTypeData){ // 选择邮政或者自主寄件  // 兼容1.3
       if(payTypeData=='ems'&& !this.state.ifYUE){
            return false;
       }
        this.setState({
            selectPayType:payTypeData
        })
    }

    handleSizeChange() { //提交
    //  localStorage.removeItem('addressList_action')
        let latest = this.state.latestData;
        let payType=this.state.payType||this.state.selectPayType;
     
   
        if (this.state.hasList == 'no') {
            Toast.info('请先添加地址', 1);
            return false;
        }
        if (!latest.provinceName || !latest.cityName || !latest.location) {
            Toast.info('地址信息不完整请重新填写', 2)
            return false;
        }
        if (this.state.selectPayType=='ems'&&latest.provinceName!='广东省') {
            // 兼容1.3
            Toast.info('邮政上门取件，仅支持广东省', 2)
            return false;
        }

      
        let postData = {
            orderId: this.orderId,
            userAddress:latest.provinceName +latest.cityName+ latest.areaName+ latest.location,
            mailType: payType,
            name: latest.name,
            phone: latest.phone,
        };
        Toast.hide();
        Toast.loading("", 30, () => Toast.info("网络错误", 2));
        getDataService.confirmAddress(postData).then(data => {
            Toast.hide();
            //console.log(data)
            if (data.code == 1000) {
               if (  data.data.resultFlag==1) {
             //   Toast.success('提交成功', 2);
                this.context.router.push('sendTheAddress/' + payType + '/' + 'btn' + '/' + this.props.params.orderId);
                }else {
                    Toast.success('提交失败，请再次提交', 2);
                }
            } else {
                Toast.info(data.msg);
            }
        });

        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Sendbackaddresspage_ClickNext' });
    }

    //添加地址
    addAddress(){
        let payTypeData =this.state.selectPayType=='ems'||this.state.payType=='ems'? 'ems':'person';
        if( this.state.latestAddrIndex == 5 ){
            Toast.info("您添加的地址已满5个，请删除后再添加", 3, () => this.context.router.push('addressList/' + this.orderId + '/' + payTypeData));
        }
        else{
            //此处做了两次跳转，目的是为了添加地址后能顺利回退到地址列表，不增加多余的浏览器记录
            this.context.router.push('addressList/' + this.orderId + '/' + payTypeData);
            this.context.router.push('addAddress/' + this.orderId + '/' + payTypeData);
        }
        SendCxytjMessage.sendMessage({ eventId: 'H5_E_Sendbackaddresspage_ClickAddaddress' });
    }

    render() {
        let res = this.state.latestData;
        let payTypeData =this.state.selectPayType=='ems'||this.state.payType=='ems'? 'ems':'person'

        //   console.log('--------res-------',res)

        return (
            <div>
                <div className={style.mailingAddress}>
                    <PageBar title="填写回寄地址" isHome={this.props.params.isClose == 'shut' ? true : false} />
                   

                    {/*本人地址选择 start*/}
                    <div className={style.title}>年检办理完成后，相关资料将会寄送至如下地址</div>
                      <div className={style.envelope} > 
                        {
                            this.state.hasList == 'no' ?
                                <div>
                                    <div className={style.add_box}
                                        onClick={() => {
                                            this.addAddress();
                                        }}>
                                        <img className={style.add_img} src="./images/add-to.png" alt="" />
                                        <div className={style.add_information}>
                                            <p>添加收件人信息</p>
                                        </div>
                                    </div>
                                </div> :

                                <div onClick={() => {
                                    this.context.router.push('addressList/' + this.orderId + '/' + payTypeData);
                                    SendCxytjMessage.sendMessage({ eventId: 'H5_E_Sendbackaddresspage_ClickChooseaddress' });
                                }}>
                                    <div className={style.name_a}>
                                        <span>{res.name}</span>
                                        <span>{res.phone}</span>
                                    </div>
                                    <p className={style.address}>
                                        <span>{res.provinceName}</span><span>{res.cityName}</span>
                                        <span>{res.areaName}</span><span>{res.location}</span>
                                    </p>
                                </div>
                        }

                        {
                            this.state.hasList == 'no' ? '' :
                                <img className={style.right_arr} src="./images/right-arr.png" alt="" />
                        }
                    </div>

                     {/**
                     * 公司收件地址
                     */}
                  {/*  {
                        this.state.mailAdd.receiveAddress != '' &&
                        <div style={{ marginBottom: this.state.payType != '' ?'100px':'' }}>
                            <div className={style.title}>请将您的车辆年检资料邮寄至以下地址</div>
                            <div className={style.envelope}>
                                <div className={style.name_a}>
                                    <span>{this.state.mailAdd.receiveName}</span>
                                    <span>{this.state.mailAdd.receivePhone}</span>
                                </div>
                                <p className={style.address}>
                                    <span>{this.state.mailAdd.receiveAddress}</span>
                                </p>
                            </div>
                        </div>
                    }*/}
                    
                    {/**
                     * 兼容1.3
                     */}
                      {
                            this.state.payType == '' &&
                                 <div className={style.mailingType} style={{marginTop:'12px', marginBottom:'100px'}}>
                                      <div className='darkgray ptb20 font-26' style={{borderBottom:'1px solid #f6f6f6'}}>请选择寄送年检资料的方式</div>
                                    <div className={style.name_list}  style={{opacity:this.state.ifYUE?1:.4, borderBottom:'1px solid #f6f6f6'}} onClick={()=>this.selectPayTypeFun('ems')}>
                                        <img className={style.choice_img}
                                            src={this.state.selectPayType=='ems' &&this.state.ifYUE?'./images/select-true.png':'./images/select-false.png'} />
                                        <div className={style.name_choice }>
                                            <p>邮政上门取件（仅限广东省）</p>
                                            <p>采用邮政上门取件的方式，大概需要5个工作日来办理年检手续（邮政快递员最迟将会在1个工作日内上门收件）。本服务只对广东用户开放</p>
                                        </div>
                                    </div>
                                    <div className={style.name_list} onClick={()=>this.selectPayTypeFun('person')}>
                                        <img className={style.choice_img}
                                            src={this.state.selectPayType!='ems'?'./images/select-true.png':'./images/select-false.png'} />
                                        <div className={style.name_choice}>
                                            <p>自主寄送资料（邮费自理）</p>
                                            <p>您需亲自寄送年检资料至车行易年检业务办理处。车行易客服人员需要2个工作日办理年检。</p>
                                        </div>
                                    </div>
                                </div>
                        }

                    <div className={style.btn_box + ' ' + style.btn_box_bottom}>
                        <Button className={style.btn_inspection} type="primary" size={'default'}
                            onClick={e => this.handleSizeChange()}>下一步</Button>
                    </div>
                </div>
            </div>
        )
    }
}

//使用context
MailingAddress.contextTypes = {
    router: React.PropTypes.object.isRequired
};


export default connect()(MailingAddress)